package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    /**
     * 用户登录
     * @param loginDto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto loginDto) {
        String password = loginDto.getPassword();
        String phone = loginDto.getPhone();
        if (StringUtils.isEmpty(password) && StringUtils.isEmpty(phone)) {
            //游客身份登录
            //生成token
            String token = AppJwtUtil.getToken(0L);
            Map map = new HashMap();
            map.put("token", token);
            return ResponseResult.okResult(map);
        }

        //账号密码登录
        //根据手机号查询数据库->判断该用户是否存在
        ApUser apUser = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, phone));
        if (apUser == null) {
            //该用户不存在 响应错误信息
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "该用户不存在");
        }

        //该用户存在 -> 判断该用户的密码是否正确
        String md5DigestAsHex = DigestUtils.md5DigestAsHex((password + apUser.getSalt()).getBytes(StandardCharsets.UTF_8));
        log.info("登录加密后的密文为: {}", md5DigestAsHex);
        if (!md5DigestAsHex.equals(apUser.getPassword())) {
            //密码错误
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        //密码正确
        Map map = new HashMap();
        String token = AppJwtUtil.getToken(Long.parseLong(apUser.getId().toString()));
        map.put("token", token);
        map.put("user", apUser);

        return ResponseResult.okResult(map);
    }
}
